/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package supermarket;


import ext_model.CreditCardAuthority;
import ext_model.ExternalBank;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.persistence.TypedQuery;
import javax.swing.JOptionPane;
import model.Checks;
import model.Customer;
import java.util.Random;
import model.Product;
import model.ProductPurchase;
import model.Purchase;
import model.Store;
import static supermarket.SuperMarket.CHECK_POINTS_LIMIT;
import static supermarket.SuperMarket.em;
import static supermarket.SuperMarket.em2;

/**
 *
 * @author root
 */
public class PayForm extends javax.swing.JFrame {

    /**
     * Creates new form PayForm
     */
    Customer customer;          //ο πελάτης
    Store store;                //το κατάστημα που θα γίνει η αγορά
    HashMap hm;                 //hashmap με τα προ´ιόντα και τις ποσότητες
    List<Integer> checksList;   //λίστα με τις επιταγές που θα ακυρωθούν
    String points;              //πόντοι
    String total;               //σύνολο
    Boolean delivery;           //παράδοση
    int tries=0;                //λάθος προσπάθειες
    
    
    public PayForm() {
        initComponents();
        fillComboBox();
    }

    public PayForm(Customer customer,Store store,HashMap hm,List<Integer> checksList,
            String points,String total,Boolean delivery) {
        this.customer=customer;
        this.checksList=checksList;
        this.hm=hm;
        this.store=store;
        this.points=points;
        this.total=total;
        this.delivery=delivery;
        initComponents();
        fillComboBox();
        fillCustomer();
    }
    
    
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        SuperMarketPU2EntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("SuperMarketPU2").createEntityManager();
        externalBankQuery = java.beans.Beans.isDesignTime() ? null : SuperMarketPU2EntityManager.createQuery("SELECT e FROM ExternalBank e");
        externalBankList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : externalBankQuery.getResultList();
        externalBankQuery1 = java.beans.Beans.isDesignTime() ? null : SuperMarketPU2EntityManager.createQuery("SELECT e FROM ExternalBank e");
        externalBankList1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : externalBankQuery1.getResultList();
        jButton1 = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jComboBox1 = new javax.swing.JComboBox();
        jPanel5 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();

        jButton1.setText("jButton1");

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 517, Short.MAX_VALUE)
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 25, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel3.setBackground(java.awt.Color.orange);
        jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jLabel5.setBackground(java.awt.Color.white);
        jLabel5.setFont(new java.awt.Font("Cantarell", 1, 36)); // NOI18N
        jLabel5.setForeground(java.awt.Color.red);
        jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/supermarket/cart.png"))); // NOI18N
        jLabel5.setText("SUPER MARKET");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(122, Short.MAX_VALUE)
                .addComponent(jLabel5)
                .addGap(85, 85, 85))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel5)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(21, 12, 590, -1));

        jPanel1.setBackground(java.awt.Color.yellow);
        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel1.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/supermarket/users.png"))); // NOI18N
        jLabel1.setText("ΠΛΗΡΩΜΗ");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(236, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addGap(181, 181, 181))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(21, 150, 590, -1));

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel2.setText("Κάτοχος:");

        jLabel3.setText("Αρ. πιστωτικής:");

        jLabel4.setText("CVV:");

        jLabel6.setText("Τράπεζα:");

        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(65, 65, 65)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel6)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 382, Short.MAX_VALUE)
                    .addComponent(jTextField2)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(20, 20, 20)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addContainerGap(36, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(21, 229, 590, -1));

        jPanel5.setBackground(java.awt.Color.lightGray);
        jPanel5.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jButton2.setText("Πληρωμή");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Ακύρωση");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 470, 280, 50));

        jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/supermarket/background.png"))); // NOI18N
        getContentPane().add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(-90, -10, 720, 550));

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // Πληρωμή
        
        
        
        //βρίσκω την πιστωτική με τον αριθμό της από την εξωτερική βάση
        TypedQuery<CreditCardAuthority> q = em2.createNamedQuery("CreditCardAuthority.findByNumber", CreditCardAuthority.class);
       q.setParameter("number", customer.getCreditCard());
       CreditCardAuthority extcustomer = q.getSingleResult();
       
       //βρίσκω την τράπεζα με το όνομά της από την εξωτερική βάση
       TypedQuery<ExternalBank> q1 = em2.createNamedQuery("ExternalBank.findByName", ExternalBank.class);
       q1.setParameter("name", customer.getBank());
       ExternalBank extbank = q1.getSingleResult();
       
       //έλεγχος για τα στοιχεία
       
       if (extcustomer.getNumber().equals(jTextField2.getText())&&
               extcustomer.getOwnerName().equals(jTextField1.getText())&&
               extcustomer.getCvv().equals(jTextField3.getText())&&
               extbank.getName().equals(jComboBox1.getSelectedItem())
               ){
            float total1 = Float.parseFloat(total);
            int points1 = Integer.parseInt(points);
           
           
           
           Purchase purchase = new Purchase();
           purchase.setCustomer(customer);
           purchase.setStore(store);
           Date date = new Date();
           purchase.setDatetime(date);
           purchase.setAmount(total1);
           purchase.setPointsEarned(points1);
           purchase.setDelivery(delivery);
           
            List<ProductPurchase> productPurchaseList = new ArrayList<>();
           
           //Δημιουργία λίστας productPurchaseList από το hashmap
            
           Iterator iter = hm.keySet().iterator();
while(iter.hasNext()) {
    Integer key = (Integer)iter.next();
                Integer quantity = (Integer) hm.get(key);
                ProductPurchase pp = new ProductPurchase();
                TypedQuery<Product> q2 = em.createNamedQuery("Product.findByProductId", Product.class);
                q2.setParameter("productId", key);
                Product product1 = q2.getSingleResult();
                pp.setProductId(product1);
                pp.setPurchaseId(purchase);
                pp.setQuantity(quantity);
                
               productPurchaseList.add(pp);
           
}
           purchase.setProductPurchaseList(productPurchaseList);
           em.persist(purchase); 
           
           
           //ακύρωση επιταγών
       if (checksList!=null){
               for (int i=0;i<checksList.size();i++){
                TypedQuery<Checks> q3 = em.createNamedQuery("Checks.findByCode", Checks.class);
           q3.setParameter("code", checksList.get(i));
                Checks check = q3.getSingleResult();
              check.setValid("ΟΧΙ");
             em.persist(check);
              
               }
           }
           
           //νεές επιταγές
              
               if((customer.getAvailablePoints()+purchase.getPointsEarned())>=CHECK_POINTS_LIMIT){
                   
                   int noOfChecksEarned = (customer.getAvailablePoints()+purchase.getPointsEarned())/CHECK_POINTS_LIMIT;
                   
                   if(noOfChecksEarned>0)
                        JOptionPane.showMessageDialog(rootPane, "Έχετε κερδίσει "+noOfChecksEarned
                        +" επιταγές!");
                   
                   Random rand = new Random();       
       
                    
                   for (int i=0;i<noOfChecksEarned;i++){
                       
                       Checks check = new Checks();
                       check.setCode(rand.nextInt(9999 - 1000));
                       check.setDatetime(date.toString());
                       check.setValid("ΝΑΙ");
                       check.setOwner(customer);
                       em.persist(check);
                       
                   }
                   
                   
                   customer.setAvailablePoints
        (customer.getAvailablePoints()+purchase.getPointsEarned()-noOfChecksEarned*CHECK_POINTS_LIMIT);
                   
               }
               
                             
               else
                   
               customer.setAvailablePoints
        (customer.getAvailablePoints()+purchase.getPointsEarned());
               
               
          // em.persist(customer);
           
           em.persist(purchase); 
           
          em.getTransaction().commit();
          
           
           
           
            JOptionPane.showMessageDialog(rootPane, "Η αγορά ολοκληρώθηκε!");
           
            PurchaseForm purchaseForm = new PurchaseForm(customer);
           purchaseForm.setVisible(true);
           dispose();
           
                   
           }
           
          
       
       else {
                 
         JOptionPane.showMessageDialog(rootPane, "Λάθος στοιχεία πιστωτικής!");
         tries=tries+1;
         if(tries==3){
             JOptionPane.showMessageDialog(rootPane, "Έχετε κάνει 3 προσπάθειες λάθος!");
            em.getTransaction().rollback();
             
             LoginForm loginForm = new LoginForm();
            loginForm.setVisible(true);
            dispose();
            
            
        }
         
        
       }
       
    }//GEN-LAST:event_jButton2ActionPerformed

    
    
    
    
    
    
    
    
    
    
    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        
        em.getTransaction().rollback();
        CustomerMenuForm customerMenuForm = new CustomerMenuForm(customer);
        customerMenuForm.setVisible(true);
        dispose();
        
    }//GEN-LAST:event_jButton3ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PayForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PayForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PayForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PayForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new PayForm().setVisible(true);
            }
        });
    }

    
    
     public void fillComboBox(){//Εισάγει τα ονόματα των τραπεζών στο ComboBox
        
        TypedQuery<ExternalBank> q = em2.createNamedQuery("ExternalBank.findAll", ExternalBank.class);
        List<ExternalBank> storesList = q.getResultList();
        
      
        for (int i=0;i<storesList.size();i++){
            
        jComboBox1.addItem(storesList.get(i).getName());
        
        }
       
        
    }
    
    
    public void fillCustomer(){
        
        jTextField1.setText(customer.getCcOwner());
        jTextField2.setText(customer.getCreditCard());
        jTextField3.setText(customer.getCvv().toString());
        
        
    }
    
    
    
    
    
    
    
    
    
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.persistence.EntityManager SuperMarketPU2EntityManager;
    private java.util.List<ext_model.ExternalBank> externalBankList;
    private java.util.List<ext_model.ExternalBank> externalBankList1;
    private javax.persistence.Query externalBankQuery;
    private javax.persistence.Query externalBankQuery1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    // End of variables declaration//GEN-END:variables
}
